package server.mypackage;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.HttpServlet;
import server.Servlet;
import server.myclassloader.ClassLoaderOne;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

/**
 * @author wuyuhan
 * @date 2020/12/16 11:09
 */
public class LoadConfig {
    private ServerConfig serverConfig;

    public LoadConfig() {
        this.serverConfig = new ServerConfig();
    }

    public ServerConfig parseConfig(){
        InputStream resourceAsStream = ClassLoaderOne.class.getClassLoader().getResourceAsStream("server.xml");
        Document document = null;
        try {
            document = new SAXReader().read(resourceAsStream);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element rootElement = document.getRootElement();
        //1、放入port
        List<Element> selectNodes = rootElement.selectNodes("//Connector");
        for (Element element : selectNodes) {
            // <servlet-name>lagou</servlet-name>
            String port = element.attributeValue("port");
            serverConfig.setPort(port);
        }

        List<Element> list = rootElement.selectNodes("//Host");
        for (Element element : list) {
            // <servlet-name>lagou</servlet-name>
            String appBase = element.attributeValue("appBase");
            serverConfig.setBasePath(appBase);
        }
        getPathClassFile(serverConfig.getBasePath());
        return serverConfig;
    }

    private void  getPathClassFile(String path){
        try {
            File rootFile = new File(path);
            File[] files = rootFile.listFiles();
            for (File file : files) {
                Document document = getDocument(file.getPath() + "/web.xml");
                Element rootElement = document.getRootElement();
                List<Element> selectNodes = rootElement.selectNodes("//servlet");
                for (int i = 0; i < selectNodes.size(); i++) {
                    Element element =  selectNodes.get(i);
                    // <servlet-name>lagou</servlet-name>
                    Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                    String servletName = servletnameElement.getStringValue();
                    // <servlet-class>server.LagouServlet</servlet-class>
                    Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                    String servletClass = servletclassElement.getStringValue();

                    // 根据servlet-name的值找到url-pattern
                    Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                    // /lagou
                    String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                    //进行设置/demo1/lagou
                    String mapKey="/"+file.getName()+urlPattern;
                    String classStr=file.getPath()+servletClass.replace(".","/")+".class";

                    ClassLoaderOne myClassLoader = new ClassLoaderOne(classStr);
                    //类的全称
                    String packageNamePath = servletClass;

                    //加载Log这个class文件
                    Class<?> httpServlet = myClassLoader.loadClass(packageNamePath);
                    Object newInstance = httpServlet.newInstance();

                    serverConfig.getServletMap().put(mapKey, (HttpServlet) newInstance);
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    private Document getDocument(String path){
        Document document=null;
        try {
        File srcFile = new File(path);
        //2 创建文件字节输入流对象，并接在源上
        InputStream resourceAsStream = new FileInputStream(srcFile);
        //InputStream resourceAsStream = ClassLoaderOne.class.getClassLoader().getResourceAsStream(name);
        document = new SAXReader().read(resourceAsStream);
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        }
        return document;
    }

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        String classPath="E:\\lagouProject\\webapps\\demo2\\server\\LagouServlet.class";
        ClassLoaderOne myClassLoader = new ClassLoaderOne(classPath);
        //类的全称
        String packageNamePath = "server.LagouServlet";

        //加载Log这个class文件
        Class<?> Log = myClassLoader.loadClass(packageNamePath);
        Object newInstance = Log.newInstance();
        System.out.println(newInstance);

        System.out.println("类加载器是:" + Log.getClassLoader());


    }
}
